package com.gitee.mrj.aiboot.core.util;

import com.gitee.mrj.aiboot.annotation.config.sf.type.AlainField;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotatedElementUtils;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class ReflectionUtils {

    public static List<Field> findAllAlainFields(Class<?> clazz) {
        return FieldUtils.getAllFieldsList(clazz).stream()
                .filter(field ->
                        Objects.nonNull(AnnotatedElementUtils.findMergedAnnotation(field, AlainField.class)))
                .collect(Collectors.toList());
    }

    /**
     * 获取字段类型或则字段的泛型类型
     *
     * @param field
     * @return
     * @throws Exception
     */
    public static Class getResolvableType(Field field) throws Exception {
        ResolvableType resolvableType = ResolvableType.forField(field);
        if (resolvableType.isArray()) {
            return resolvableType.getComponentType().resolve();
        }
        Class<?> rawClass = resolvableType.getRawClass();
        if (Collection.class.isAssignableFrom(rawClass)) {
            return resolvableType.getGeneric(0).resolve();
        }
        return resolvableType.resolve();
    }

}
